package com.morder.databases;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.morder.Info;

public class DbAdapter {

  private static final String TAG = "yangbo";
  private Context mContext;
  private static final int DATABASE_VERSION = 1;
  private static final String DATABASE_NAME = "morder.db";
  private DatabaseHelper mHelper;
  private SQLiteDatabase mSqLiteDatabase;
  
  public final static byte[] _writeLock = new byte[0];

  private static class DatabaseHelper extends SQLiteOpenHelper {

    public DatabaseHelper(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public DatabaseHelper(Context context, String name, CursorFactory factory, int version) {
      super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      Log.d(TAG, "onCreate");
      createInfoDb(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      db.execSQL("DROP TABLE IF EXISTS infoList");
      onCreate(db);
    }
    
    private void createInfoDb(SQLiteDatabase db){
      StringBuffer sb = new StringBuffer();
      sb.append("CREATE TABLE [infoList] (");
      sb.append("[id] INTEGER(13) NOT NULL DEFAULT (0), ");
      sb.append("[image] NVARCHAR(200) NOT NULL DEFAULT (''), ");
      sb.append("[value] CHAR(10) NOT NULL DEFAULT(''))");
      
      db.execSQL(sb.toString());
    }
  }

  public DbAdapter(Context context) {
    this.mContext = context;
  }

  public DbAdapter open() {
    mHelper = new DatabaseHelper(mContext);
    mSqLiteDatabase = mHelper.getWritableDatabase();
    return this;
  }

  public void close() {
    mSqLiteDatabase.close();
  }
  
  /**
   * 插入
   * @param list
   */
  public void SynchronyData2DB(List<Info> infoList) {
    List<ContentValues> list = new ArrayList<ContentValues>();
    for (int i = 0, len = infoList.size(); i < len; i++) {
      ContentValues contentValues = new ContentValues();
      contentValues.put("id", infoList.get(i).getId());
      contentValues.put("image", infoList.get(i).getImage());
      contentValues.put("value", infoList.get(i).getValue());
      list.add(contentValues);
    }
    synchronized (_writeLock) {
      mSqLiteDatabase.beginTransaction();
      try {
        // 清除已有
        // String where="IsFull=?";
        // String[] args={"0"};
        // db.delete(DB_BLOG_TABLE, where, args);
        for (int i = 0, len = list.size(); i < len; i++) {
          int id = list.get(i).getAsInteger("id");
          boolean isExist = exist(id);
          if (!isExist) {
            mSqLiteDatabase.insert("infoList", null, list.get(i));
          }
        }
        mSqLiteDatabase.setTransactionSuccessful();
      } catch(Exception e){
        e.printStackTrace();
      } finally {
        mSqLiteDatabase.endTransaction();
      }
    }
  }
  
  /**
   * 判断是否已经存在
   * @param orderId
   * @return
   */
  private boolean exist(int id) {
    String where = "id=?";
    String[] args = { String.valueOf(id) };
    Cursor cursor = mSqLiteDatabase.query("infoList", null, where, args, null, null, null);
    boolean isExist = cursor != null && cursor.moveToNext();
    if (cursor != null) {
      cursor.close();
      cursor = null;
    }
    return isExist;
  }
  
  public ArrayList<Info> getInfoListByPage(int pageIndex, int pageSize){
    String limit = String.valueOf((pageIndex) * pageSize) + ","
        + String.valueOf(pageSize);
    ArrayList<Info> list = getInfoListByWhere(limit, null, null);
    
    return list;
  }
  
  public ArrayList<Info> getInfoListByWhere(String limit, String where, String[] args){
    ArrayList<Info> listBuy = new ArrayList<Info>();
    String orderBy = "id desc";
    Cursor cursor = mSqLiteDatabase.query("infoList", null, where, args, null, null, orderBy, limit);
    while (cursor != null && cursor.moveToNext()) {
      Info buy = new Info();
      int id = cursor.getInt(cursor.getColumnIndex("id"));
      String image = cursor.getString(cursor.getColumnIndex("image"));
      String value = cursor.getString(cursor.getColumnIndex("value"));
      buy.setId(id + "");
      buy.setImage(image);
      buy.setValue(value);
      listBuy.add(buy);
    }
    if (cursor != null) {
      cursor.close();
      cursor = null;
    }
    return listBuy;
  }
}